package algorithm.sort;

import algorithm.utils.Integers;
import com.sun.media.sound.SoftTuning;
import org.junit.Test;

/**
 * @author cyt
 * @create 2020-08-23 18:50
 */
public class Bubbling {

    /**
     * 冒泡排序
     * 特点： 不管序列是否有序， 都会把当前序列中的元素逐个比较一遍。
     * 优化1： 如果当前的序列已经是有序了， 就直接停止排序。此优化的前提是当前序列在排序的过程中可能会出现有序的情况。
     */

    @Test
    public void Bubbling2Test() {
        int[] arr = Integers.getArr(1000, 1, 10000);
        long beginTime = System.currentTimeMillis();

        int end = arr.length - 1;
        for (int i = end; i > 0; i--) {
            int sortIndex = 0;
            for (int begin = 1; begin <= end; begin++) {
                if (arr[begin] < arr[begin - 1]) {
                    int temp = arr[begin];
                    arr[begin] = arr[begin - 1];
                    arr[begin - 1] = temp;
                    sortIndex = begin;
                }
            }
            end = sortIndex;
        }
        System.out.println(beginTime);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime);
        System.out.println("time is -> " + (endTime - beginTime));

        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    @Test
    public void Bubbling1Test() {
        int[] arr = Integers.getArr(1000, 1, 10000);
        long begin = System.currentTimeMillis();
        for (int i = 0; i < arr.length; i++) {
            boolean isSort = true;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    isSort = false;
                }
            }
            if (isSort) {
                break;
            }
        }
        System.out.println(begin);
        long end = System.currentTimeMillis();
        System.out.println(end);
        System.out.println("time is -> " + (end - begin));
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    @Test
    public void Bubbling3Test() {
        int[] arr = Integers.getArr(1000, 1, 10000);
        long begin = System.currentTimeMillis();
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        System.out.println(begin);
        long end = System.currentTimeMillis();
        System.out.println(end);
        System.out.println("time is -> " + (end - begin));
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }

    @Test
    public void test() {
        int[] arr = Integers.getArr(100, 1, 1000);
        for (int i : arr) {
            System.out.println(i);
        }
    }

}
